package main

import (
	"context"
	"fmt"
	_ "github.com/mbobakov/grpc-consul-resolver" // It's important
	"github.com/opentracing/opentracing-go"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"jaeger-demo/common"
	"jaeger-demo/otgrpc"
	"jaeger-demo/proto"
	"jaeger-demo/utils"
	"log"
)

func main() {
	// 第一步：获取Tracer
	tracer, closer := utils.GetTracer()
	defer closer.Close()

	// 第二步：把tracer设置为全局，以后使用opentracing.GlobalTracer()开启span即可或opentracing.StartSpan()开启span
	opentracing.SetGlobalTracer(tracer)

	conn, err := grpc.Dial(
		fmt.Sprintf("consul://%s/grpc_test?wait=14s&tag=lqz", common.ConsulAddr),
		//grpc.WithInsecure(),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
		// 加入一个拦截器，传入OpenTracingClientInterceptor的配置
		// opentracing.GlobalTracer()等同于上面的tracer
		grpc.WithUnaryInterceptor(otgrpc.OpenTracingClientInterceptor(opentracing.GlobalTracer())),
	)

	if err != nil {
		log.Fatal(err)
	}

	defer conn.Close()

	client := proto.NewGreeterClient(conn)

	// 测试默认值
	resp, err := client.SayHello(context.Background(), &proto.HelloRequest{
		Name: "lqz",
		Age:  19,
	})

	if err != nil {
		panic(err)
	}

	fmt.Println(resp.Reply)
}
